<template>
  <div>
    <el-button type="danger" @click="addSpecial">新增专题</el-button>

    <el-row :gutter="10" :style="{ 'margin-top': '10px' }">
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>专题</span>
            </div>
          </template>
          <el-table :data="filterTableData" style="width: 100%" @rowClick="rowClick">
            <el-table-column label="封面" prop="cover" width="110">
              <template v-slot:default="scope">
                <Cover :cover="scope.row.cover"></Cover>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="specialName" width="120" />
            <el-table-column label="简介" prop="specialDesc" />
            <el-table-column label="博客数量" prop="blogCount" width="80" />
            <el-table-column label="操作" width="150">
              <template #header>
                <el-input v-model="search" size="small" placeholder="Type to search" class="search-input" />
              </template>
              <template v-slot="{ row }">
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>专题文章</span>
            </div>
          </template>
          <!-- 右侧文章表格展示 -->
          <el-table :data="blogList" style="width: 100%">
            <el-table-column prop="title" label="文章标题" />
            <el-table-column label="操作" width="200">
              <template v-slot="{ row }">
                <el-button size="small" @click="showDetail(row)">预览</el-button>
                <el-button size="small" @click="editBlog('edit', row)">修改</el-button>
                <el-button size="small" type="danger" @click="delBlog(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑按钮点击后的弹窗-->
    <el-dialog
        v-model="dialogVisible"
        title="修改专题信息"
        width="30%"
        draggable
    >
      <!-- 添加一个标题说明 -->
      <p style="font-size: 14px; color: #888; margin-bottom: 10px;">
        请修改专题的封面、名称和简介，并保存更改。
      </p>

      <!-- 第一段：封面 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题封面：
    </span>
        <CoverUpload
            v-model="rowData.cover"
            @update:filename="onFilenameUpdate"
        ></CoverUpload>
      </div>

      <!-- 第二段：分类名称 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题名称：
    </span>
        <el-input
            v-model="rowData.specialName"
            placeholder="请输入专题名称"
            style="height: 30px; font-size: 16px;"
        />
      </div>

      <!-- 第三段：分类简介 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题简介：
    </span>
        <el-input
            v-model="rowData.specialDesc"
            placeholder="请输入专题简介（最多 300 字）"
            class="multiline-input"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4 }"
            :maxlength="300"
        />
      </div>

      <!-- 底部操作按钮 -->
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="dialogVisible"
        title="修改专题信息"
        width="30%"
        draggable
    >
      <!-- 添加一个标题说明 -->
      <p style="font-size: 14px; color: #888; margin-bottom: 10px;">
        请修改专题的封面、名称和简介，并保存更改。
      </p>

      <!-- 第一段：封面 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题封面：
    </span>
        <CoverUpload
            v-model="rowData.cover"
            @update:filename="onFilenameUpdate"
        ></CoverUpload>
      </div>

      <!-- 第二段：分类名称 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题名称：
    </span>
        <el-input
            v-model="rowData.specialName"
            placeholder="请输入专题名称"
            style="height: 30px; font-size: 16px;"
        />
      </div>

      <!-- 第三段：分类简介 -->
      <div style="margin-bottom: 10px;">
    <span style="font-size: 14px; font-weight: bold; display: block; margin-bottom: 5px;">
      专题简介：
    </span>
        <el-input
            v-model="rowData.specialDesc"
            placeholder="请输入专题简介（最多 300 字）"
            class="multiline-input"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4 }"
            :maxlength="300"
        />
      </div>

      <!-- 底部操作按钮 -->
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave2">保存</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed} from "vue";
import axios from "axios";

const rowData = ref({
  cover: "",
  specialName: "",
  specialDesc: "",
});
const jwtToken = localStorage.getItem("jwtToken");

const axiosInstance = axios.create({
  headers: {
    Token: jwtToken, // 将JWT令牌放入请求头的token字段
  },
});

const savedData = ref([]);
const dialogVisible = ref(false);
const tableData = ref([]);
const tableDataData = computed(() =>
    tableData.filter(
        (data) =>
            !(ref("")).value || data.specialName.toLowerCase().includes(ref("").value.toLowerCase())
    )
);
// 发起请求并将数据赋值给tableData展示表格数据
axiosInstance
    .get("http://localhost:8080/specialdata/show")
    .then((response) => {
      const responseData = response.data;
      if (Array.isArray(responseData.data) && responseData.data.length > 0) {
        tableData.value = responseData.data; // 赋值给tableData
      }
    })
    .catch((error) => {
      console.error("请求失败:", error);
    });
const search = ref("");
const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value || // 修改这里
            data.specialName.toLowerCase().includes(search.value.toLowerCase()) // 修改这里
    )
);
const handleEdit = (row) => {
  // 复制选定行的数据到 rowData
  rowData.value = {...row};
  dialogVisible.value = true;
  console.log(rowData.value);
};

const addSpecial=(row)=>{
  dialogVisible.value = true;
  console.log(row)
}
const showDetail = (row) => {
  // 拼接目标 URL，row.blogId 是动态 ID
  const targetUrl = `http://localhost:3002/homePage/${row.blogId}`;

  // 使用 `window.location.href` 跳转页面
  window.location.href = targetUrl;
};

// 文章操作
const editBlog = (action, blogItem) => {
  // 拼接目标 URL，row.blogId 是动态 ID
  const targetUrl = `http://localhost:3002/blog/list`;

  // 使用 `window.location.href` 跳转页面
  window.location.href = targetUrl;
};
const delBlog = (blogItem) => {
  console.log("删除文章：", blogItem.title);
};

const handleSave = () => {
  // 将编辑后的数据添加到 savedData 中
  savedData.value.push({...rowData.value});
  console.log(rowData.value);
  dialogVisible.value = false;
  // 发起请求并将数据赋值给tableData展示表格数据
  axiosInstance
      .put("http://localhost:8080/specialdata/update", rowData.value)
      .then((response) => {
        const responseData = response.data;
        console.log(responseData.data);
        alert("保存成功");
        // 刷新页面
        location.reload();
        // 其他处理逻辑
      })
      .catch((error) => {
        console.error("请求失败:", error);
      });
};

const handleSave2=()=>{
  // 将编辑后的数据添加到 savedData 中
  savedData.value.push({...rowData.value});
  console.log(rowData.value);
  dialogVisible.value = false;
  // 发起请求并将数据赋值给tableData展示表格数据
  axiosInstance
      .post("http://localhost:8080/specialdata/addSpecial", rowData.value)
      .then((response) => {
        const responseData = response.data;
        console.log(responseData.data);
        alert("保存成功");
        // 刷新页面
        location.reload();
        // 其他处理逻辑
      })
      .catch((error) => {
        console.error("请求失败:", error);
      });
}
// 删除按钮点击时执行的逻辑
const handleDelete = (row) => {
  console.log("删除按钮点击，处理删除逻辑，当前行数据：", row.specialName);
  axiosInstance
      .delete(`http://localhost:8080/specialdata/delete/${row.specialName}`)
      .then((response) => {
        // 处理删除成功的逻辑
      })
      .catch((error) => {
        // 处理删除失败的逻辑
      });
};

// 专题文章表格数据
const blogList = ref([]);
const rowClick = (row) => {
  console.log(row.categoryId);
  axiosInstance
      .get(`http://localhost:8080/showSpecialData/${row.specialId}`)
      .then((response) => {
        blogList.value = response.data.data; // 更新文章数据
        console.log(response.data.data);
      })
      .catch((error) => {
        console.error("请求失败:", error);
      });
};

</script>

<style lang="scss">
.multiline-input {
  margin-bottom: 10px;
  height: 120px;
  font-size: 16px;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  resize: vertical;
  text-align: left;
}
</style>
